package site.wanjiahao.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import site.wanjiahao.constant.FileConstant;
import site.wanjiahao.entity.FileEntity;
import site.wanjiahao.mapper.FileMapper;
import site.wanjiahao.service.FileService;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Service
public class FileServiceImpl extends ServiceImpl<FileMapper, FileEntity> implements FileService {


    @Override
    public String upload(String rootPath, MultipartFile file) throws IOException {

        // TODO 考虑是否可以使用异步方式处理上传文件, 对于大文件来说对用户体验不是很好
        String[] results = uploadToServer(rootPath, file);

        saveToDB(file, results);

        return results[1];
    }

    // 保存文件元数据至数据库
    private void saveToDB(MultipartFile file, String[] storePath) {
        FileEntity fileEntity = new FileEntity();

        // 文件创建时间，更新时间由mybatis拦截插件处理
        fileEntity.setFileId(storePath[1]);
        fileEntity.setFilePath(storePath[0]);
        fileEntity.setFileSize(file.getSize());
        fileEntity.setOriginName(file.getOriginalFilename());
        fileEntity.setFileType(file.getContentType());

        // 保存至数据库
        baseMapper.insert(fileEntity);
    }

    // 上传文件至服务器
    private String[] uploadToServer(String rootPath, MultipartFile file) throws IOException {
        // 类路径
        URL classResource = this.getClass().getClassLoader().getResource("");
        assert classResource != null;
        String classResourcePath = classResource.getPath().substring(1);
        String dir = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        Path storeDirPath = Paths.get(classResourcePath, rootPath, dir);
        if (Files.notExists(storeDirPath)) {
            // 不存在创建根目录
            Files.createDirectories(storeDirPath);
        }
        // 设置随机上传文件名称
        String filename = UUID.randomUUID().toString().replaceAll("-", "");
        String uuid = filename;
        String originalFilename = file.getOriginalFilename();
        int index;
        // 后缀添加
        if (!StringUtils.isEmpty(originalFilename) && (index = originalFilename.lastIndexOf(".")) != -1) {
            filename += originalFilename.substring(index);
        }
        Path path = Paths.get(storeDirPath.toString(), filename);
        file.transferTo(path);
        return new String[]{path.toString(), uuid};
    }

    @Override
    public String upload(MultipartFile file) throws IOException {
       return upload(FileConstant.UPLOAD_ROOT_PATH, file);
    }

    @Override
    public FileEntity getAbsoluteFilePathByUUID(String uuid) throws FileNotFoundException {
        FileEntity fileEntity = baseMapper.selectById(uuid);
        if (fileEntity == null) {
            throw new FileNotFoundException();
        }
        return fileEntity;
    }

    @Override
    public FileEntity findByUUID(String uuid) {
        return baseMapper.selectById(uuid);
    }


}
